package com.ldy.core.web;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ldy.core.common.Result;
import com.ldy.core.entity.BaseFile;
import com.ldy.core.service.BaseFileService;

/**
 * 文件管理
 */
@RestController
@RequestMapping("/file")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class FileController {
	
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);

	@Autowired
	private BaseFileService fileService;
	
	/**
	 * 上传
	 * @return
	 */
	@PostMapping("/upload")
	public Result upload(@RequestParam("file") MultipartFile file, BaseFile vo) {
		logger.info("upload: {}", JSONObject.toJSONString(vo));
		try (InputStream inputStream = file.getInputStream()) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			IOUtils.copy(inputStream, bos);
			vo.setContent(Base64.getEncoder().encodeToString(bos.toByteArray()));
			vo.setCreateTime(new Date());
			fileService.save(vo);
			return Result.success();
		}catch (Exception e) {
			logger.error("", e);
			return Result.failure(e.getMessage());
		}
	}
	
	/**
	 * 下载
	 * @param id
	 * @param response
	 * @return
	 */
	@GetMapping("/download")
	public ResponseEntity<Object> download(String id, HttpServletResponse response) {
		logger.debug("request:{}, params:[id:{}]", "下载", id);
		try {
			BaseFile file = fileService.getById(id);
			Assert.notNull(file, "不存在下载文件");
			// 下载
			ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(file.getContent()));
			Resource resource = new InputStreamResource(bis);
			String  encodedFileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString());
			return ResponseEntity.ok()
					.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"")
					.contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
		} catch (Exception e) {
			logger.error("下载异常: {}", e);
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.failure(e.getMessage()));
		}
	}

	/**
	 * 获取 base64
	 * @return
	 */
	@PostMapping("/getBase64")
	public Result getBase64(String id) {
		BaseFile file = fileService.getById(id);
		return Result.success(file.getContent());
	}
	
	
	/**
	 * 列表查询
	 * @return
	 */
	@PostMapping("/selectList")
	public Result selectList(String refId, String type) {
		QueryWrapper<BaseFile> query = new QueryWrapper<>();
		query.eq("ref_id", refId);
		if (StringUtils.hasText(type)) {
			query.eq("type", type);
		}
		query.select("id", "type", "name", "size", "ref_id", "create_time");
		query.orderByDesc("create_time");
		return Result.success(fileService.list(query));
	}
	/**
	 * 删除
	 * 
	 * @return
	 */
	@PostMapping("/delete")
	public Result delete(String id) {
		logger.info("method: {}, params:[id: {}]", "delete", id);
		fileService.removeById(id);
		return Result.success();
	}
}
